package net.caixiaomi.info.widgets;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.view.SupportMenuInflater;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import net.caixiaomi.info.R;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseDialogFragment;
import net.caixiaomi.info.helper.AppHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 分享对话框
 */

public class BottomHandleDialogFragment extends BaseDialogFragment {
    public static final String TAG = "BOTTOM_TAG";
    public static final int LIST = 0x10;
    public static final int GRID = 0x11;

    @BindView(android.R.id.list)
    RecyclerView mRecyclerView;

    @BindView(R.id.header)
    LinearLayout mHeader;

    @BindView(R.id.footer)
    LinearLayout mFooter;

    private int mLayoutType = GRID;
    private int mMenu = -1;
    private List<Integer> mHeaderList;
    private List<Integer> mFooterList;
    private OnItemClickListener mListener;


    public BottomHandleDialogFragment() {
        mHeaderList = new ArrayList<Integer>();
        mFooterList = new ArrayList<Integer>();
    }

    @OnClick(R.id.btn_cancel)
    void toCancel() {
        dismiss();
    }

    @Override
    protected int layoutRes() {
        return R.layout.dialog_bottom;
    }

    @Override
    protected void onViewCreated(@NonNull View view) {
        if (mMenu == -1) {
            return;
        }
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wlp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        wlp.gravity = Gravity.BOTTOM;
        window.setAttributes(wlp);
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        window.setBackgroundDrawable(new ColorDrawable(0xff000000));
        getDialog().getWindow().setLayout(dm.widthPixels, getDialog().getWindow().getAttributes().height);

        MenuInflater menuInflater = new SupportMenuInflater(getContext());
        MenuBuilder menuBuilder = new MenuBuilder(getContext());
        menuInflater.inflate(mMenu, menuBuilder);
        List<Item> items = new ArrayList<>();
        for (int index = 0; index < menuBuilder.size(); index++) {
            MenuItem item = menuBuilder.getItem(index);
            items.add(new Item(item.getItemId(), item.getTitle().toString(), item.getIcon()));
        }

        RecyclerView.LayoutManager manager;
        if (mLayoutType == LIST) {
            manager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        } else if (mLayoutType == GRID)
            manager = new GridLayoutManager(getContext(), 4);
        else {
            manager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        }
        DialogAdapter adapter = new DialogAdapter(items, mLayoutType);
        adapter.setItemClickListener(mListener);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        for (int header : mHeaderList) {
            View headerView = LayoutInflater.from(CommonApp.getInstance()).inflate(header, null);
            mHeader.addView(headerView);
        }
        mHeader.setVisibility(mHeaderList.isEmpty() ? View.GONE : View.VISIBLE);

        for (int footer : mFooterList) {
            View headerView = LayoutInflater.from(CommonApp.getInstance()).inflate(footer, null);
            mFooter.addView(headerView);
        }
        mFooter.setVisibility(mFooterList.isEmpty() ? View.GONE : View.VISIBLE);

    }

    public void setLayoutType(int layout_type) {
        mLayoutType = layout_type;
    }

    public void setMenu(int menu) {
        mMenu = menu;
    }

    public void setItemClickListener(OnItemClickListener onItemClickListener) {
        this.mListener = onItemClickListener;
    }

    public void addHeader(List header) {
        if (!header.isEmpty()) {
            mHeaderList.addAll(header);
        }
    }

    public void addFooter(List footer) {
        if (!footer.isEmpty()) {
            mFooterList.addAll(footer);
        }
    }

    /**
     * dialog点击item接口
     */
    public interface OnItemClickListener {
        void onItemClick(View view);
    }


    private static class Item {
        private int id;
        private String title;
        private Drawable icon;

        public Item() {
        }

        public Item(int id, String title, Drawable icon) {
            this.id = id;
            this.title = title;
            this.icon = icon;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public Drawable getIcon() {
            return icon;
        }

        public void setIcon(Drawable icon) {
            this.icon = icon;
        }

    }

    /**
     * recycler view adapter, provide HORIZONTAL and LIST item style
     */
    private static class DialogAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private List<Item> mItems = Collections.emptyList();
        private OnItemClickListener mListener;
        private int layout;

        DialogAdapter(List<Item> mItems, int layout) {
            setList(mItems);
            this.layout = layout;
        }

        private void setList(List<Item> items) {
            mItems = items == null ? new ArrayList<Item>() : items;
        }

        void setItemClickListener(OnItemClickListener onItemClickListener) {
            this.mListener = onItemClickListener;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            TextView view = new TextView(parent.getContext());
            if (layout == GRID)
                return new GridViewHolder(view);
            else {
                return new LinearViewHolder(view);
            }
        }

        private Drawable icon(Drawable drawable) {
            if (drawable != null) {
                Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                @SuppressWarnings("SuspiciousNameCombination") Drawable resizeIcon = new BitmapDrawable(CommonApp.getInstance().getResources(), Bitmap.createScaledBitmap(bitmap, (int) CommonApp.getInstance().getResources().getDimension(R.dimen.padding_38), (int) CommonApp.getInstance().getResources().getDimension(R.dimen.padding_38), true));
                Drawable.ConstantState state = resizeIcon.getConstantState();
                resizeIcon = DrawableCompat.wrap(state == null ? resizeIcon : state.newDrawable().mutate());
                return resizeIcon;
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            final Item item = mItems.get(position);
            TextView view = (TextView) holder.itemView;
            view.setId(item.getId());
            view.setText(item.getTitle());
            view.setCompoundDrawablesWithIntrinsicBounds(null, layout == GRID ? icon(item.getIcon()) : null, null, null);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mListener != null) mListener.onItemClick(view);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mItems.size();
        }

        /**
         * horizontal item adapter
         */
        private static class GridViewHolder extends RecyclerView.ViewHolder {

            GridViewHolder(View view) {
                super(view);
                TextView textView = (TextView) view;
                ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.width = AppHelper.getScreenWidth(view.getContext()) / 4;
                params.height = AppHelper.getScreenWidth(view.getContext()) / 4;

                textView.setLayoutParams(params);

                textView.setMaxLines(1);
                textView.setEllipsize(TextUtils.TruncateAt.END);
                textView.setGravity(Gravity.CENTER);
                textView.setTextColor(ContextCompat.getColor(view.getContext(), R.color.black));
                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, view.getContext().getResources().getDimension(R.dimen.font_10));
                textView.setCompoundDrawablePadding((int) view.getContext().getResources().getDimension(R.dimen.padding_5));
                textView.setPadding(0, (int) view.getContext().getResources().getDimension(R.dimen.padding_12), 0, (int) view.getContext().getResources().getDimension(R.dimen.padding_12));

                TypedValue typedValue = new TypedValue();
                view.getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, typedValue, true);
                textView.setBackgroundResource(typedValue.resourceId);
            }
        }

        private static class LinearViewHolder extends RecyclerView.ViewHolder {

            LinearViewHolder(View view) {
                super(view);
                TextView textView = (TextView) view;
                ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                textView.setLayoutParams(params);

                textView.setMaxLines(1);
                textView.setEllipsize(TextUtils.TruncateAt.END);
                textView.setGravity(Gravity.CENTER);
                textView.setTextColor(ContextCompat.getColor(view.getContext(), R.color.black));
                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, view.getContext().getResources().getDimension(R.dimen.font_14));
                textView.setPadding(0, (int) view.getContext().getResources().getDimension(R.dimen.padding_12), 0, (int) view.getContext().getResources().getDimension(R.dimen.padding_12));

                TypedValue typedValue = new TypedValue();
                view.getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground, typedValue, true);
                textView.setBackgroundResource(typedValue.resourceId);

            }
        }
    }

}
